var rf_guid = null;
var rf_cookiePrefix = 'rf';
var rf_historyId = '#rf_history';
var rf_history_click_funName = 'rf_history_click';
jQuery(document).ready(function ($) {
    checkIsRunState(rf_cookiePrefix, function (guid) {
        rf_guid = guid;
        $("#RF-execute").text('运行中...');
        $('#RF-execute').attr('disabled', 'disabled');
        $(rf_historyId).hide();
        rf_polling();
    });

    initHistoryDropDownMenu(rf_cookiePrefix, rf_historyId, rf_history_click_funName);
    // addItemToHistory(rf_cookiePrefix, rf_historyId, 'test123', new Date(), rf_history_click_funName);

    function setRfRunState(isRun) {
        if (isRun) {
            $("#RF-execute").text('运行中...');
            $('#RF-execute').attr('disabled', 'disabled');
            $(rf_historyId).hide();
            setRunState(rf_cookiePrefix, true, rf_guid);
        } else {
            $('#RF-execute').removeAttr('disabled');
            $(rf_historyId).show();
            $("#RF-execute").text('运行');
            setRunState(rf_cookiePrefix, false);
        }
    }

    //点击运行 执行算法 成功后获得path
    $("#RF-execute").click(function (event) {
        //$("#RF-execute").attr('disabled', true);
        rf_guid = WebUploader.Base.guid();
        $.ajax({
            url: 'algorithm/RandomForest.do',
            type: 'POST',
            dataType: 'json',
            async: true,
            contentType: 'application/x-www-form-urlencoded',
            data: {
                guid: rf_guid
            },
            beforeSend: function () {
                setRfRunState(true);
            },
            success: function (path) {
                if (!path.status) {
                    rf_polling();
                } else {
                    alert(path.msg);
                    setRfRunState(false);
                }
            },
            error: function () {
                alert("网络繁忙，请稍后再试！");
                setRfRunState(false);
            }
        });
    });

    //轮询检测算法是否完成
    function rf_polling() {
        $.ajax({
            url: 'data/checkRandomForest.do',
            type: 'POST',
            async: true,
            dataType: 'json',
            data: {
                guid: rf_guid
            },
            success: function (result) {
                //成功
                if (!result.status) //因为后台数据status为1 所以暂时把!result.status的！ 去掉了！
                {
                    setRfRunState(false);
                    setTable(); //成功后就获取YS1的值

                    addItemToHistory(rf_cookiePrefix, rf_historyId, rf_guid, new Date(), rf_history_click_funName);
                } else if (result.msg != 'no') {
                    alert("服务器报错：" + result.msg);
                    setRfRunState(false);
                }
                //不成功 轮询
                else {
                    window.setTimeout(function () {
                        rf_polling()
                    }, 30000);
                }
            },
            error: (function () {
                alert("轮询出错");
                setRfRunState(false);
            })
        })
    }

    function setTable() {
        $.ajax({
            url: 'data/getRFData.do',
            type: 'POST',
            async: true,
            dataType: 'json',
            data: {
                guid: rf_guid
            },
            success: function (result) {
                if (!result.status) {
                    console.log(result);
                    createTable(result.data.values);

                    var execRes = {
                        accuary: result.data.accuary,
                        kappa: result.data.kappa,
                        reliability: result.data.reliability,
                        reliability_sd: result.data.reliability_sd
                    };
                    var rfResult = $('#rf-result');
                    rfResult.html();
                    for(var name in execRes){
                        rfResult.append('<label class="col-sm-2 control-label">' + name +'：</label><p class="col-sm-10 control-label">' + execRes[name] + '</p>');
                    }

                } else {
                    alert(result.msg);
                }
            },
            error: function () {
                alert("表格失败!");
            }
        })
    }

    function createTable(tableData) {
        var i, j;
        var rTable = document.getElementById("rf-table");
        rTable.innerHTML = '<caption>混淆矩阵</caption>';
        for (i in tableData) {
            var tr = rTable.insertRow(i);
            for (j in tableData[i]) {
                var td = tr.insertCell(j);
                if (i == 0 && j == 0) {
                    // td.innerHTML = '<div class="cause-table-line">' +
                    //     '<table class="inner-table">' +
                    //     '</table>' +
                    //     '</div>';
                } else {
                    td.innerHTML = tableData[i][j];
                }
            }
        }
        j++;
        var persent = 100 / j;
        var tableWidth = persent.toString();
        tableWidth += "%";
        $(".cause-table td").css({
            width: tableWidth,
            minwidth: '10%'
        });
    }
});

function rf_history_click(sender) {
    rf_guid = $(sender).attr('value');
    fpg_getYS1();
}